package com.haust.community.controller;

import com.aliyun.oss.OSS;
import com.haust.community.annotation.LoginRequired;
import com.haust.community.config.AliyunOssConfig;
import com.haust.community.pojo.User;
import com.haust.community.service.FileUploadService;
import com.haust.community.service.FollowService;
import com.haust.community.service.LikeService;
import com.haust.community.service.UserService;
import com.haust.community.utils.CommunityConstant;
import com.haust.community.utils.CommunityUtil;
import com.haust.community.utils.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Auther: csp1999
 * @Date: 2020/11/24/21:39
 * @Description: 用户相关Controller
 */
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private OSS ossClient;// 注入阿里云oss文件服务器客户端
    @Autowired
    private AliyunOssConfig aliyunOssConfig;// 注入阿里云OSS基本配置类

    @Value("${community.upload}")
    private String uploadPath;

    @Value("${community.path}")
    private String path;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 账号设置页面
     *
     * @return
     */
    @LoginRequired
    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    public String getSettingPage() {
        return "/site/setting";
    }

    /**
     * 头像上传操作(基于OSS的头像上传,推荐使用)
     *
     * @param: file
     * @return: com.alibaba.fastjson.JSONObject
     * @create: 2020/10/31 17:35
     * @author: csp1999
     */
    @LoginRequired
    @RequestMapping(path = "/ossUpload", method = RequestMethod.POST)
    public String ossUploadHeader(
            @RequestParam("headerImage") MultipartFile headerImage, Model model) {

        if (headerImage != null) {
            String returnFileUrl = fileUploadService.upload(headerImage);
            if (returnFileUrl.equals("error")) {
                model.addAttribute("error", "文件上传失败！");
                return "/site/setting";
            }

            logger.info("文件上传成功！");

            User user = hostHolder.getUser();
            String headerUrl = returnFileUrl;

            userService.updateHeader(user.getId(), headerUrl);

            return "redirect:/index";
        } else {
            model.addAttribute("error", "您还没有选择图片!");
            return "/site/setting";
        }
    }

    /**
     * 更新头像路径
     * @param fileName
     * @return
     */
//    @RequestMapping(path = "/header/url", method = RequestMethod.POST)
//    @ResponseBody
//    public String updateHeaderUrl(String fileName) {
//        if (StringUtils.isBlank(fileName)) {
//            return CommunityUtil.getJSONString(1, "文件名不能为空!");
//        }
//
//        String url = headerBucketUrl + "/" + fileName;
//        userService.updateHeader(hostHolder.getUser().getId(), url);
//
//        return CommunityUtil.getJSONString(0);
//    }

    /**
     * 头像上传操作(原生的头像上传,不推荐再使用)
     *
     * @param headerImage
     * @param model
     * @return
     */
    @Deprecated // 声明该方法不推荐使用，该方法上会带有横线
    @LoginRequired
    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            model.addAttribute("error", "您还没有选择图片!");
            return "/site/setting";
        }

        String fileName = headerImage.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件的格式不正确!");
            return "/site/setting";
        }

        // 生成随机文件名
        fileName = CommunityUtil.generateUUID() + suffix;
        // 确定文件存放的路径
        File dest = new File(uploadPath + "/" + fileName);
        try {
            // 存储文件
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败: " + e.getMessage());
            throw new RuntimeException("上传文件失败,服务器发生异常!", e);
        }

        // 更新当前用户的头像的路径(web访问路径)
        // http://csp1999.natapp1.cc/community/user/header/xxx.png
        User user = hostHolder.getUser();
        String headerUrl = path + contextPath + "/user/header/" + fileName;
        userService.updateHeader(user.getId(), headerUrl);

        return "redirect:/index";
    }

    /**
     * 获取头像(原生的获取头像方法,不推荐使用了)
     *
     * @param fileName
     * @param response
     */
    @Deprecated // 声明该方法不推荐使用，该方法上会带有横线
    @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        // 服务器存放路径
        fileName = uploadPath + "/" + fileName;
        // 文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败: " + e.getMessage());
        }
    }

    /**
     * 个人主页
     *
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }

        // 用户
        model.addAttribute("user", user);

        // 用户累计获得的点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        // 关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);

        // 粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);

        // 当前登录用户对某个用户是否已关注
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {// 未登录用户，默认是没有关注
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);

        return "/site/profile";
    }
}
